import os
import json
import uuid
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import os
import json
import uuid

class ToolCreate(BaseModel):
    name: str
    endpoint: str
    description: str = ''
    tool_code: str = ''

TOOLS_DIR = os.path.join(os.path.dirname(__file__), 'task_tools')

def ensure_tools_dir():
    if not os.path.exists(TOOLS_DIR):
        os.makedirs(TOOLS_DIR)

router = APIRouter(prefix="/api/tools", tags=["Tools Management"])

@router.get('/list')
async def get_tools():
    ensure_tools_dir()
    tools = []
    for filename in os.listdir(TOOLS_DIR):
        if filename.endswith('.py'):
            file_path = os.path.join(TOOLS_DIR, filename)
            with open(file_path, 'r') as f:
                first_line = f.readline().strip()
                if first_line.startswith('# METADATA: '):
                    meta = json.loads(first_line[12:])
                    tools.append(meta)
    return {'code': 200, 'data': tools}

@router.post('/create')
async def create_tool(tool_data: ToolCreate):
    if not tool_data.name or not tool_data.endpoint:
        raise HTTPException(status_code=400, detail='缺少必填参数')

    tool_id = str(uuid.uuid4())
    meta = {
        'id': tool_id,
        'name': tool_data.name,
        'description': tool_data.description,
        'endpoint': tool_data.endpoint
    }
    
    ensure_tools_dir()
    try:
        with open(os.path.join(TOOLS_DIR, f'{tool_id}.py'), 'w') as f:
            f.write(f'# METADATA: {json.dumps(meta)}\n')
            f.write(tool_data.tool_code)
        return {'code': 201, 'data': meta}
    except Exception as e:
        raise HTTPException(status_code=500, detail='文件创建失败')

@router.put('/update/{tool_id}')
async def update_tool(tool_id: str, tool_data: ToolCreate):
    file_path = os.path.join(TOOLS_DIR, f'{tool_id}.py')
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail='工具不存在')

    try:
        with open(file_path, 'r+') as f:
            content = f.read().split('\n', 1)
            existing_meta = json.loads(content[0][12:])
            
            new_meta = {
                **existing_meta,
                'name': tool_data.name,
                'description': tool_data.description,
                'endpoint': tool_data.endpoint
            }
            
            f.seek(0)
            f.write(f'# METADATA: {json.dumps(new_meta)}\n')
            f.write(tool_data.tool_code if tool_data.tool_code else content[1])
            f.truncate()
        return {'code': 200, 'data': new_meta}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f'操作失败: {str(e)}')

@router.delete('/delete/{tool_id}')
async def delete_tool(tool_id: str):
    file_path = os.path.join(TOOLS_DIR, f'{tool_id}.py')
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail='工具不存在')

    try:
        os.remove(file_path)
        return {'code': 204, 'message': '工具已删除'}
    except Exception as e:
        raise HTTPException(status_code=500, detail='文件删除失败')

